package model

import (
	"fmt"
	"io/ioutil"
	"path"
	"time"

	"github.com/nfnt/resize"
)

// 压缩的文件格式
type CompressFile struct {
	File
	SavedSize     int64         `json:"savedSize"`     // 大小
	CompressRatio string        `json:"compressRatio"` // 压缩率
	Status        string        `json:"status"`        // 压缩状态
	Duration      time.Duration `json:"duration"`      // 耗时
}

type CompressFileConfig struct {
	Config
	Target string `json:"target"` // 保存的格式
}

// 压缩信息
type CompressSession struct {
	Total    int           `json:"total"`
	TodoNum  int           `json:"todoNum"`
	Duration time.Duration `json:"duration"`
}

// 图片压缩
func (f *CompressFile) CompressImages(c CompressFileConfig) (err error) {
	if c.Target == "default" {
		f.OutMimeType = f.MimeType
	} else {
		f.OutMimeType = c.Target
	}
	if c.OutDirType == "1" {
		f.OutDir = c.OutDir
	} else {
		f.OutDir = f.Location
	}
	err = f.Decode()
	if err != nil {
		return err
	}
	m := resize.Resize(0, 0, f.Image, resize.Lanczos3)
	f.Image = m
	dest := path.Join(f.OutDir, c.Prefix+f.NameOnly+c.Suffix+"."+f.OutMimeType)
	err = f.Encode()
	if err != nil {
		return err
	}
	SavedSize := int64(f.Buf.Len())
	if f.OutMimeType == f.MimeType && SavedSize >= f.Size {
		return fmt.Errorf("无法压缩")
	}
	f.SavedSize = SavedSize

	err = ioutil.WriteFile(dest, f.Buf.Bytes(), 0666)
	if err != nil {
		return err
	}

	return nil
}
